package main

import (
	"bufio"
	"encoding/json"
	"log"
	"net"
	"time"
)

type StatusReq struct {
	Id     int `json:"id"`
	Status int `json:"status"`
	Ver    int `json:"ver"`
}

type CommonResult struct {
	Ret int
	Msg string
}

func main() {
	go func() {
		<-time.After(time.Second * 3)
		client()
	}()
	testTcp()
}

func testTcp() {

	//服务端在本机8888端口建立tcp监听

	listener, err := net.Listen("tcp", "127.0.0.1:8888")
	log.Println(err, "net.listen")
	if err != nil {
		log.Fatal(err)
	}
	for {
		//循环接入所有客户端得到专线连接
		conn, e := listener.Accept()
		log.Println(e, "listener.accept")
		//开辟独立协程处理请求
		go handleRequest(conn)
	}

}

func handleRequest(conn net.Conn) {
	defer func() {
		log.Println("关闭当前连接", conn.RemoteAddr().String())
		conn.Close()
	}()
	reader := bufio.NewReader(conn)
	for {
		b, err := reader.ReadString('\n')
		log.Println("收到客户端的信息")
		if err != nil {
			log.Println("server read error", err)
			return
		}
		log.Println(string(b))
		rsp := CommonResult{
			Ret: 1,
			Msg: "success",
		}
		data, _ := json.Marshal(rsp)
		data = append(data, byte('\n'))
		conn.Write(data)
	}
}

func client() {
	conn, err := net.Dial("tcp", "127.0.0.1:8888")
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	req := StatusReq{
		Id:     1,
		Status: 4,
		Ver:    1,
	}
	data, err := json.Marshal(req)
	log.Println("json", conn.LocalAddr().String(), string(data), err)
	// io.WriteString(conn, string(data))
	data = append(data, byte('\n'))
	conn.Write(data)
	reader := bufio.NewReader(conn)
	for {
		b, err := reader.ReadString('\n')
		log.Println("收到服务端的信息")
		if err != nil {
			log.Println("client read error", err)
			return
		}
		log.Println(string(b))
		return
	}
}
